﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.IO;
using Abp.Timing;
using Abp.UI;
using AbpZeroTemplate.Url;
using DotCommon.Utility;

namespace AbpZeroTemplate.Dfs
{
    /// <summary>文件存储系统
    /// </summary>
    public class DfsStorage : IDfsStorage, ITransientDependency
    {
        public IAppFolders AppFolders { get; set; }
        public IWebUrlService WebUrlService { get; set; }


        /// <summary>保存到临时文件夹
        /// </summary>
        public async Task<TemporaryFile> SaveTemporaryFile(byte[] data, string extension)
        {
            return await SaveTemporaryFile(data, ObjectId.GenerateNewStringId(), extension);
        }

        /// <summary>保存到临时目录下
        /// </summary>
        public async Task<TemporaryFile> SaveTemporaryFile(byte[] data, string name, string extension)
        {
            DirectoryHelper.CreateIfNotExists(AppFolders.TemporaryFolder);
            //保存的文件路径
            var savePath = Path.Combine(AppFolders.TemporaryFolder, $"{name}{extension}");
            using (FileStream fw = File.OpenWrite(savePath))
            {
                await fw.WriteAsync(data, 0, data.Length);
            }
            return CreateTemporaryFileFromFile(name, extension);
        }

        /// <summary>保存到真实路径
        /// </summary>
        public async Task<StorageFile> SaveStorageFile(byte[] data, string name, string extension)
        {
            //保存的目录,存储 dfs/storage/year/month
            var savePath = Path.Combine(AppFolders.StorageRootFolder, $"{Clock.Now.Year}{Path.DirectorySeparatorChar}{Clock.Now.Month}");
            DirectoryHelper.CreateIfNotExists(savePath);
            using (FileStream fw = File.OpenWrite(savePath))
            {
                await fw.WriteAsync(data, 0, data.Length);
            }
            var virtualPath = $"{Clock.Now.Year}/{Clock.Now.Month}";
            return CreateStorageFile(virtualPath, name, extension);
        }

        /// <summary>将临时文件保存到真实文件目录
        /// </summary>
        public async Task<StorageFile> SaveStorageFile(string temporaryFileName)
        {
            var temporaryFileNameArr = temporaryFileName.Split('.');
            var localPath = Path.Combine(AppFolders.TemporaryFolder, temporaryFileName);
            if (!File.Exists(localPath))
            {
                throw new UserFriendlyException($"文件不存在");
            }
            var data = File.ReadAllBytes(localPath);
            return await SaveStorageFile(data, temporaryFileNameArr[0], temporaryFileNameArr[1]);
        }

        /// <summary>从保存路径获取文件
        /// </summary>
        public StorageFile GetStorageFileFromSavePath(string savePath)
        {
            var index = savePath.LastIndexOf('/');
            var fileName = savePath.Substring(index);
            var fileNameArr = fileName.Split('.');
            var virtualPath = savePath.Substring(0, savePath.Length - fileName.Length);
            return CreateStorageFile(virtualPath, fileNameArr[0], $".{fileNameArr[1]}");
        }

        /// <summary>根据虚拟路径,名称,扩展名获取存储的真实文件信息
        /// </summary>
        private StorageFile CreateStorageFile(string virtualPath, string name, string extension)
        {
            var url = $"{WebUrlService.GetStorageRootFolderUrl()}/{virtualPath}";
            var storageFile = new StorageFile()
            {
                Name = name,
                Extension = extension,
                Mime = MimeTypeNameUtil.GetMimeName(extension),
                Url = url
            };
            storageFile.SavePath = $"{virtualPath}/{name}{extension}";
            storageFile.LocalFullName = GetLocalFullName(virtualPath, name, extension);
            if (IsPicture(extension))
            {
                storageFile.DownloadUrl = storageFile.Url;
            }
            else
            {
                storageFile.DownloadUrl = "";
            }

            return storageFile;
        }


        /// <summary>根据文件名称创建临时文件数据
        /// </summary>
        private TemporaryFile CreateTemporaryFileFromFile(string name, string extension)
        {
            //获取文件扩展名
            var temporaryFile = new TemporaryFile()
            {
                Name = name,
                Extension = extension,
                Mime = MimeTypeNameUtil.GetMimeName(extension),
                Url = $"{WebUrlService.GetTemporaryFolderUrl()}/"
            };
            var url = $"{WebUrlService.GetTemporaryFolderUrl()}/{temporaryFile.GetFileName()}";
            if (IsPicture(extension))
            {
                temporaryFile.DownloadUrl = temporaryFile.Url;
            }
            else
            {
                temporaryFile.DownloadUrl = "";
            }
            return temporaryFile;
        }

        /// <summary>是否为图片
        /// </summary>
        private bool IsPicture(string extension)
        {
            if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
            {
                return true;
            }
            return false;
        }

        /// <summary>将虚拟路径转换为全路径
        /// </summary>
        private string GetLocalFullName(string virtualPath, string name, string extension)
        {
            var virtualPathArr = virtualPath.Split('/');
            return Path.Combine(AppFolders.StorageRootFolder, $"{virtualPathArr[0]}{Path.DirectorySeparatorChar}{virtualPathArr[1]}{Path.DirectorySeparatorChar}{name}{extension}");
        }



    }
}
